package com.bookrecomm.controller;

import com.bookrecomm.entity.User;
import com.bookrecomm.service.UserService;
import com.bookrecomm.vo.ResultVO;
import com.bookrecomm.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 * 处理用户信息相关的请求
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取当前登录用户信息
     * @return 用户信息
     */
    @GetMapping("/me")
    @PreAuthorize("isAuthenticated()")
    public ResultVO<UserVO> getCurrentUser() {
        UserVO userVO = userService.getCurrentUser();
        return ResultVO.success("获取成功", userVO);
    }

    /**
     * 根据ID查询用户信息
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or #id == authentication.principal.id")
    public ResultVO<UserVO> getUserById(@PathVariable Long id) {
        UserVO userVO = userService.findById(id);
        return ResultVO.success("获取成功", userVO);
    }

    /**
     * 更新用户信息
     * @param id 用户ID
     * @param user 用户信息
     * @return 更新后的用户信息
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or #id == authentication.principal.id")
    public ResultVO<UserVO> updateUser(
            @PathVariable Long id,
            @RequestBody User user) {
        
        UserVO userVO = userService.updateUser(id, user);
        return ResultVO.success("更新成功", userVO);
    }

    /**
     * 更新用户密码
     * @param id 用户ID
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 更新结果
     */
    @PutMapping("/{id}/password")
    @PreAuthorize("hasRole('ADMIN') or #id == authentication.principal.id")
    public ResultVO<Boolean> updatePassword(
            @PathVariable Long id,
            @RequestParam String oldPassword,
            @RequestParam String newPassword) {
        
        boolean success = userService.updatePassword(id, oldPassword, newPassword);
        return ResultVO.success("密码更新成功", success);
    }
}
